package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmSensitiveDto;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {
    /**
     * 分页查询
     * @param dto
     * @return
     */
    @Override
    public ResponseResult list(WmSensitiveDto dto) {
        dto.checkParam();
        //分页查询
        IPage<WmSensitive> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper<>();
        //模糊查询敏感词
        queryWrapper.like(StringUtils.isNotEmpty(dto.getName()),WmSensitive::getSensitives,dto.getName());
        //按照时间倒序排序
        queryWrapper.orderByDesc(WmSensitive::getCreatedTime);
        page(page, queryWrapper);
        //封装数据
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(), dto.getSize(),page.getTotal());
        responseResult.setData(page.getRecords());
        return responseResult;
    }

    /**
     * 新增敏感词
     * @param wmSensitive
     * @return
     */
    @Override
    public ResponseResult saveWmSensitive(WmSensitive wmSensitive) {
        List<WmSensitive> list = list();
        //判断敏感词是否已存在
        for (WmSensitive sensitive : list) {
            if (sensitive.getSensitives().equals(wmSensitive.getSensitives())){
                //响应错误信息,数据已经存在
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
            }
        }
        //不存在,保存敏感词
        wmSensitive.setCreatedTime(new Date());
        save(wmSensitive);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
